package com.xhwl.logistics.component;

import com.xhwl.common.exception.BusinessException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "address")
public class VehicleHomeAddressProperty {

    private List<Map<String, Map<String, String>>> name;

    @Setter(AccessLevel.NONE)
    @Getter(AccessLevel.NONE)
    private Map<String, String> config;

    @PostConstruct
    private void init() {
        System.out.println("Hello World!");

        Map<String, String> tempMap = new HashMap<>(512);
        name.forEach(map -> map.forEach((k1, v1) -> v1.forEach((k2, v2) -> tempMap.put(k1+k2, v2))));

        config = Collections.unmodifiableMap(tempMap);
    }

    public String getHomeAddress(String name) {
        String string = config.get(name);
        if (null == string) {
            return "/";
        }
        return string;
    }

    public String getLocalPlateName(String homeAddress) {
        List<String> localPlateNameList = config.entrySet().stream().filter(entry -> homeAddress.contains(entry.getValue())).map(Map.Entry::getKey).collect(Collectors.toList());
//        if (localPlateNameList.size()!=1) {
//            //后续可以优化关于这四个地址的判断
//            if (homeAddress.contains("北京") || homeAddress.contains("天津") || homeAddress.contains("上海") || homeAddress.contains("重庆")) {
//                return localPlateNameList.get(0);
//            } else {
//                throw new BusinessException("项目地址不是行政地区找不到匹配本地车牌地址或者找到多个地址");
//            }
//        } else {
//            return localPlateNameList.get(0);
//        }
        StringBuilder localPlateName = new StringBuilder();
        String localPlateStr = ",";
        if(!localPlateNameList.isEmpty()){
            for (String plateStr : localPlateNameList) {
                localPlateName.append(plateStr).append(",");
            }
            localPlateStr = localPlateName.toString();
        }else{
            throw new BusinessException("通过项目地址找不到车牌地址！");
        }
        return localPlateStr.substring(0,localPlateStr.length()-1);
    }

}
